const express = require("express");
const app = express();
const path = require('path');
const crypto = require("crypto");
// 解析表单数据 (application/x-www-form-urlencoded)
app.use(express.urlencoded({ extended: true }));
// 解析 JSON 数据（可选）
app.use(express.json());

let balance = 1000;

app.use((req, res, next) => {
  // 任何页面都不能用 iframe/frame/embed 等方式加载当前页面
  // res.setHeader('X-Frame-Options', 'DENY')
  // res.setHeader('Content-Security-Policy', "frame-ancestors 'none'");
  next()
})

app.get('/', (req, res) => {
    const name = req.query.name || "guest"
    // 直接输出未转义的用户输入
    res.send(`<script>alert("Hello, ${name}")</script>`)
})


app.get('/a.html', (req, res) => {
  res.sendFile(path.join(__dirname, './index.html'))
})


// 模拟登录接口，给浏览器种 cookie
app.get("/login", (req, res) => {
  // 给浏览器设置一个 Cookie，表示用户已登录
  res.setHeader(
    "Set-Cookie",
    "sessionid=123456; Path=/; HttpOnly; SameSite=Strict"
  );
  const csrfToken = crypto.randomBytes(16).toString("hex");
  res.cookie("csrf_token", csrfToken, { path: "/" });
  res.send("登录成功，已设置 Cookie: sessionid=123456<br><a href='/'>去首页</a>");
});

// 转账接口（无 CSRF 防护！）
app.post("/transfer", (req, res) => {
  const { to, amount, csrf_token } = req.body;
  if (!req.headers.cookie || !req.headers.cookie.includes("sessionid=123456")) {
    return res.status(403).send("未登录，禁止转账");
  }
  if (csrf_token !== req.cookies.csrf_token) {
    return res.status(403).send("CSRF Token 校验失败！");
  }
  console.log('cookie', req.headers.cookie)
  balance -= Number(amount);
  res.send(`已转账 ${amount} 元给 ${to}，账户余额：${balance}`);
});

// 提供一个“我的账户”页面
app.get("/balance", (req, res) => {
  const csrfToken = req.cookies.csrf_token;
  res.send(`
    <h1>我的账户</h1>
    <p>余额：${balance}</p>
    <form method="POST" action="/transfer">
      <input type="hidden" name="csrf_token" value="${csrfToken}" />
      <input type="text" name="to" placeholder="收款人" />
      <input type="number" name="amount" value="100" />
      <button type="submit">转账</button>
    </form>
  `);
});


app.listen(3000, () => {
  console.log("http://localhost:3000");
})